export type UniPlatforms = "mp-weixin" | "mp-alipay" | "mp-baidu" | "mp-toutao" | "h5";

declare var wx: Uni
declare const uni: Uni;

interface Uni {
    upx2px: Function
    getSystemInfoSync: Function
    getImageInfo: Function
}

declare global {
    interface Window {
        uni: Uni
        innerWidth: any
    }
}

// declare class Image {
//     src: string
//     onload(v: any): void;
//     onerror(v: any): void;
//     success(v: any): void;
//     fail(v: any): void;
// }


const baseFun = {
    upx2px: (upx: number) => window.innerWidth / 750 * upx,
    getSystemInfoSync: () => ({ screenWidth: window.innerWidth }),
    getImageInfo: ({ src, success, fail }: Image) => {
        const image = new Image()
        image.onload = function () {
            success({
                width: this.naturalWidth,
                height: this.naturalHeight,
                path: this.src,
                src
            })
        }
        image.onerror = fail
        image.src = src
    }
}

export const PLATFORM: UniPlatforms = (function () {
    // @ts-ignore
    if (typeof swan == "object")
        return "mp-baidu"
    if (typeof tt == "object")
        return "mp-toutao"
    if (typeof plus === 'object')
        return "plus"
    if (typeof window == "object")
        if (typeof uni == 'undefined' || typeof uni !== 'undefined' && !uni?.addInterceptor) {
            return "web"
        } else {
            return "h5"
        }
    return "mp-weixin"
})();


const _uni = (function () {
    if (PLATFORM == 'mp-weixin') {
        return wx
    }
    if (PLATFORM == 'mp-toutao') {
        return tt
    }
    if (typeof uni != "undefined") {
        if (!uni.upx2px) {
            return Object.assign(uni, baseFun)
        }
        return uni
    }
    if (typeof window != "undefined") {
        return baseFun
    }

    return uni;
})();

if (!_uni.upx2px) {
    let scale = (_uni.getSystemInfoSync().screenWidth ?? 375) / 750;
    _uni.upx2px = (rpx: number) => scale * rpx
}
export { _uni as uni }